package cn.jcet.gumall.product.exception;

import cn.jcet.common.exceptuon.BizCodeEnum;
import cn.jcet.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 鲜磊
 * @Date 2020/7/7 14:55
 */
@Slf4j
@RestControllerAdvice(basePackages = {"cn.jcet.gumall.product.controller"})
public class GuMallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();

        Map<String,String> map = new HashMap<>();
            result.getFieldErrors().forEach(item ->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
        log.error("异常信息{}，异常类{}",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.VALUEDATA_EXCEPTION.getCode(),BizCodeEnum.VALUEDATA_EXCEPTION.getMessage()).put("data",map);
    }


    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        log.error("异常是{}",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTUIN.getCode(),BizCodeEnum.UNKNOW_EXCEPTUIN.getMessage());
    }


}
